﻿using System;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Library;
using Library.MVCHelpers;
using System.Collections.Generic;
using Ecommerce.Models;

namespace Ecommerce.Controllers
{
    public class HomeController : BaseController
    {
        [Compress(Order = 1)]
        //[OutputCache(CacheProfile = "Cache60s", Order = 2)]
        public ActionResult Index(string culture)
        {
            if (!string.IsNullOrEmpty(culture) && culture == Settings.DefaultCulture)
            {
                NOWCulture.UpdateCurrentCulture(Settings.DefaultCulture);
                return RedirectPermanent("~/");
            }

            using(var db = DatabaseConnector)
            {
                var categories = db.ProductCategories;
                var lstCategoryViewModels = new List<HomeCaterogiesViewModel>();
                foreach (var item in categories)
                {
                    lstCategoryViewModels.Add(new HomeCaterogiesViewModel(item));
                }
                return View(lstCategoryViewModels);
            }
        }

        [Compress(Order = 1)]
        [OutputCache(CacheProfile = "Cache1800s", Order = 2)]
        public ActionResult Page()
        {
            var pageId = Convert.ToInt32(RouteData.Values["id"]);

            using(var db = DatabaseConnector)
            {
                var page = db.Pages.FirstOrDefault(p => p.Id == pageId);
                if (page == null)
                {
                    throw new HttpException(404, "Page not found");
                }

                var pageCulture = page.PageCultures.FirstOrDefault(pc => pc.Culture == CurrentCulture);
                if (pageCulture == null)
                {
                    throw new HttpException(404, "Page not found");
                }

                var sb = new StringBuilder();
                foreach (var pc in page.PageCultures)
                {
                    sb.AppendFormat("{0}:{1}|", pc.Culture, pc.Url);
                }
                ViewBag.HrefLangs = sb.ToString().Trim('|');

                return View(pageCulture);
            }
        }
    }
}